package main

import (
	"bufio"
	"context"
	"fmt"
	"github.com/nsqio/go-nsq"
	"log"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"
)

//初始化生产者
func initProducer(straddr string) (*nsq.Producer, error) {
	config := nsq.NewConfig()
	producer, err := nsq.NewProducer(straddr, config)
	if err != nil {
		fmt.Printf("create producer failed, err:%v\n", err)
		return nil, err
	}
	return producer, nil
}
func main() {
	nsqAddr := "127.0.0.1:4150"
	producer, err := initProducer(nsqAddr)
	if err != nil {
		fmt.Printf("init producer failed, err:%v\n", err)
		return
	}
	reader := bufio.NewReader(os.Stdin)
	for {
		data, err := reader.ReadString('\n')
		if err != nil {
			fmt.Printf("read string from stdin failed, err:%v\n", err)
			continue
		}
		data = strings.TrimSpace(data)
		if strings.ToUpper(data) == "Q" {
			break
		}
		// 向 'topic_demo' publish 数据
		err = producer.Publish("topic_demo", []byte(data))
		if err != nil {
			fmt.Printf("publish msg to nsq failed, err:%v\n", err)
			continue
		}
	}
	//这里要监听一些系统call 就像优雅关闭服务器那样
	// Gracefully stop the producer when appropriate (e.g. before shutting down the service)
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	select {
	case <-quit:
		log.Println(" program is exiting...")
		_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		producer.Stop()
	}
	log.Println(" program exit ok")
}
